package com.yunshipei.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.google.gson.Gson;
import com.yunshipei.base.BaseLoginActivity;
import com.yunshipei.common.Globals;
import com.yunshipei.common.LoginManager;
import com.yunshipei.common.ProfileHandler;
import com.yunshipei.common.exception.UserAuthException;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.common.net.api.LoginAuthApi;
import com.yunshipei.common.net.converter.JsonConverterFactory;
import com.yunshipei.core.common.DeviceInfo;
import com.yunshipei.core.common.XCloudException;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.core.utils.NetUtils;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.db.green.XCloudSign;
import com.yunshipei.db.green.XCloudSignDao;
import com.yunshipei.enterplorer.BuildConfig;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.EnterDbManager;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.EncUtils;
import com.yunshipei.utils.LogHandlerUtils;
import com.yunshipei.utils.LogUtil;
import com.yunshipei.utils.StringConverterFactory;
import com.yunshipei.utils.ToastUtils;

import org.chromiun.net.GURLUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.OnTouch;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends BaseLoginActivity {

    @Bind(R.id.rl_root_view)
    protected View mRootView;
    @Bind(R.id.rl_login_content_edit)
    protected RelativeLayout mContentEditAreaRl;
    @Bind(R.id.user_companuy_logo_img)
    protected ImageView mUserCompanyLogo;
    @Bind(R.id.et_user_name)
    protected EditText mUserNameEt;
    @Bind(R.id.iv_clear_user_name)
    protected ImageView mClearUserNameImg;
    @Bind(R.id.et_password)
    protected EditText mPasswordEt;
    @Bind(R.id.iv_clear_password)
    protected ImageView mClearPasswordImg;
    @Bind(R.id.iv_show_password)
    protected ImageView mShowPasswordImg;
    @Bind(R.id.btn_login)
    protected Button mLoginBtn;
    @Bind(R.id.tv_go_back)
    protected TextView tvGoBack;
    @Bind(R.id.tv_find_password)
    protected TextView tvFindPassword;

    private SharedPreferences mPreferences;
    private String mManagerServer;
    private String mCompanyID;
    private String mUserName;
    private String mPassword;
    private WaitDialog mWaitingDialog;

    private LoginManager mLoginManager;
    private SharedPreferences mNoClearPreferences;
    private Set<String> mCompanyNameHistory;
    //Manager账户是写死的
//    private static final String MANAGER_ACCOUNT = "17611717265";
//    private static final String MANAGER_PASSWORD = "123456qaz";
    private  String MANAGER_ACCOUNT = "13693245560";
    private  String MANAGER_PASSWORD = "123456cofcoko";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(BaseUtil.getCurrentTheme());
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        MANAGER_ACCOUNT= BuildConfig.MANAGER_ACCOUNT;
        MANAGER_PASSWORD= BuildConfig.MANAGER_PASSWORD;


        BaseUtil.modifyIndexBtnCircleBg(mLoginBtn, 8, 8, 8, 8);
        int color = EnterConfig.getInstance().getGlobalColor();
        tvGoBack.setTextColor(color);
        tvFindPassword.setTextColor(color);
        mPreferences = YspPreferences.getInstance().getSharedPreferences();
        SharedPreferences preferences = getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE);
        mManagerServer = preferences.getString(Globals.MANUAL_BASE_URL, "");
        mCompanyID = preferences.getString(Globals.SP_COMPANY_ID, "");

        mNoClearPreferences = getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE);
        mCompanyNameHistory = mNoClearPreferences.getStringSet(Globals.MY_OLD_DOMAIN_NAME_DATAS, new HashSet<String>());
        if (TextUtils.isEmpty(mManagerServer)) {
            mManagerServer = preferences.getString(Globals.SP_HUB_GET_SERVER, "");
        }
        if (TextUtils.isEmpty(mManagerServer) || TextUtils.isEmpty(mCompanyID)) {
            startActivity(new Intent(this, CompanyNameLoginActivity.class));
            finish();
        } else {
            String placeHolder = preferences.getString(Globals.SP_COMPANY_PLACE_HOLDER, getResources().getString(R.string.txt_input_account));
            mUserNameEt.setHint(placeHolder);
            String userName = mPreferences.getString(Globals.USER_NAME, "");
            mUserNameEt.setText(userName);
            mUserNameEt.setSelection(TextUtils.isEmpty(userName) ? 0 : userName.length());
            String password = "";
            String uuid = mPreferences.getString(Globals.UUID, "");
            if (!TextUtils.isEmpty(uuid)) {
                String tempPas = mPreferences.getString(Globals.PASSWORD, "");
                if (!TextUtils.isEmpty(tempPas)) {
                    password = EncUtils.decrypt(uuid, tempPas);
                }
            }
            mPasswordEt.setText(password);
            mPasswordEt.setSelection(TextUtils.isEmpty(password) ? 0 : password.length());
            if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
                mLoginBtn.setAlpha(0.6f);
            }
            final int keyHeight = this.getWindowManager().getDefaultDisplay().getHeight() / 3;
            if (!SystemUtils.isPad(this)) {
                mRootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                    @Override
                    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
                            mRootView.setPadding(0, 0, 0, 0);
                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentEditAreaRl.getLayoutParams();
                            if (layoutParams.getRules()[RelativeLayout.ALIGN_PARENT_BOTTOM] == 0) {
                                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                            }
                            mContentEditAreaRl.setLayoutParams(layoutParams);
                        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
                            mRootView.setPadding(0, getResources().getDimensionPixelOffset(R.dimen.login_root_padding), 0, 0);
                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentEditAreaRl.getLayoutParams();
                            if (layoutParams.getRules()[RelativeLayout.ALIGN_PARENT_BOTTOM] != 0) {
                                layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                            }
                            mContentEditAreaRl.setLayoutParams(layoutParams);
                        }
                    }
                });
            } else {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentEditAreaRl.getLayoutParams();
                layoutParams.width = (int) ((BaseUtil.getStandSize(this) * 4) / 5);
                mContentEditAreaRl.setLayoutParams(layoutParams);
            }
            //此处初始化是为了兼容测试工程师错误操作逻辑
            mLoginManager = new LoginManager(this);
            HttpMethods.getInstance().initManagerServer(mManagerServer);
            OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(EnterClient.getInstances().getManagerClient());
            Glide.get(this).register(GlideUrl.class, InputStream.class, factory);
            String companyLogo = preferences.getString(Globals.SP_COMPANY_LOGO, "");
          //  Glide.with(this).load(companyLogo).placeholder(R.drawable.default_img).dontAnimate().override(546, 150).into(mUserCompanyLogo);
        }
    }

    @OnClick({R.id.btn_login, R.id.iv_clear_user_name, R.id.iv_clear_password, R.id.iv_show_password, R.id.tv_go_back, R.id.tv_find_password})
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                BaseUtil.hideKeyBoard(this);
                if (!NetUtils.isNetworkAvailable(this)) {
                    ToastUtils.showToast(getString(R.string.net_no_connect));
                } else {
                    mUserName = mUserNameEt.getText().toString().trim();
                    mPassword = mPasswordEt.getEditableText().toString().trim();
                    if (mWaitingDialog == null) {
                        mWaitingDialog = DialogHelper.getNoCancelableWaitDialog(this, getString(R.string.login_loading_message));
                    }
                    mWaitingDialog.show();
                   // initHttp();
                    loginADServer(mUserName,mPassword);
                }
                break;
            case R.id.iv_clear_user_name:
                BaseUtil.hideKeyBoard(this);
                mUserNameEt.setText("");
                break;
            case R.id.iv_clear_password:
                BaseUtil.hideKeyBoard(this);
                mPasswordEt.setText("");
                break;
            case R.id.iv_show_password:
                int type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
                if (mPasswordEt.getInputType() == type) {
                    mShowPasswordImg.setImageResource(R.drawable.icon_show_password);
                    mPasswordEt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    mShowPasswordImg.setImageResource(R.drawable.icon_hide_password);
                    mPasswordEt.setInputType(type);
                }
                String text = mPasswordEt.getText().toString();
                mPasswordEt.setSelection(TextUtils.isEmpty(text) ? 0 : text.length());
                break;
            case R.id.tv_go_back:
                BaseUtil.hideKeyBoard(this);
                mPreferences.edit().putString(Globals.USER_NAME, "").putString(Globals.PASSWORD, "").apply();
                startActivity(new Intent(this, CompanyNameLoginActivity.class));
                finish();
                break;
            case R.id.tv_find_password:
                BaseUtil.hideKeyBoard(this);
                startActivity(new Intent(this, UserNameInputActivity.class).putExtra(UserNameInputActivity.EXTRA_COMPANY_ID, mCompanyID));
                break;
        }
    }

    @OnTextChanged(R.id.et_user_name)
    protected void onUserNameTextChangeEvent(Editable editable) {
        int length = editable.length();
        mClearUserNameImg.setVisibility(length > 0 ? View.VISIBLE : View.GONE);
        mLoginBtn.setAlpha((length <= 0 || TextUtils.isEmpty(mPasswordEt.getText())) ? 0.6f : 1.0f);
        mLoginBtn.setEnabled(length > 0 && !TextUtils.isEmpty(mPasswordEt.getText()));
    }

    @OnTextChanged(R.id.et_password)
    protected void onPasswordTextChangeEvent(Editable editable) {
        int length = editable.length();
        mClearPasswordImg.setVisibility(length > 0 ? View.VISIBLE : View.GONE);
        mLoginBtn.setAlpha((length <= 0 || TextUtils.isEmpty(mUserNameEt.getText())) ? 0.6f : 1.0f);
        mLoginBtn.setEnabled(length > 0 && !TextUtils.isEmpty(mUserNameEt.getText()));
    }

    @OnTouch(R.id.rl_root_view)
    protected boolean onViewTouchEvent() {
        BaseUtil.hideKeyBoard(this);
        return false;
    }


    /**
     * 初始化retrofit请求
     */
    private void initHttp() {

        EnterClient.getInstances().initManagerClient(mManagerServer + "/v2/newLogin", "", 0);
        OkHttpClient mClient = EnterClient.getInstances().getManagerClient();
        final LoginAuthApi authApi = new Retrofit.Builder().client(mClient).baseUrl(mManagerServer).
                addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
                addConverterFactory(JsonConverterFactory.create()).build()
                .create(LoginAuthApi.class);
        authApi.authCompany(mCompanyID).flatMap(new Function<JSONObject, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(JSONObject jsonObject) throws Exception {

                Log.e("json",jsonObject.toString());

                mUserName = mUserNameEt.getText().toString().trim();
                mPassword = mPasswordEt.getEditableText().toString().trim();

                int status = jsonObject.optInt("status", 0);
                String companyId = "";
                if (status == 1) {
                    JSONObject data = jsonObject.optJSONObject("data");
                    if (data != null) {
                        companyId = data.optString("companyId", "");
                    }

                    String companyID = data.optString("companyId");
                    String companyLogo = data.optString("iconUrl");
                    String placeHolder = data.optString("placeHolder");
                    String themeCode = data.optString("themeCode");
                    SharedPreferences.Editor editor = mNoClearPreferences.edit();
                    editor.putString(Globals.SP_COMPANY_ID, companyID)
                            .putString(Globals.SP_COMPANY_LOGO, companyLogo)
                            .putString(Globals.SP_COMPANY_HOST, "bsrse-test.com")
                            .putString(Globals.SP_COMPANY_THEME_CODE, themeCode)
                            .putString(Globals.SP_COMPANY_PLACE_HOLDER, placeHolder);
                    EnterConfig.getInstance().setThemeCode(themeCode);
                    if (!mCompanyNameHistory.contains("bsrse-test.com")) {
                        mCompanyNameHistory.add("bsrse-test.com");
                        editor.putStringSet(Globals.MY_OLD_DOMAIN_NAME_DATAS, mCompanyNameHistory);
                    }
                    editor.commit();


                }
                if (!TextUtils.isEmpty(companyId)) {
                    long timeStamp = System.currentTimeMillis();
                    JSONObject sdkSumSrc = new JSONObject();
                    sdkSumSrc.put("sdk", companyId);
                    // TODO: 2018/6/21 因为调试,暂时写死的账号,之后放开,用mUserName替换
                    sdkSumSrc.put("deviceId", MANAGER_ACCOUNT);
                    sdkSumSrc.put("timestamp", timeStamp);
                    String sdkSum = GURLUtils.getSDKSum(sdkSumSrc.toString());
                    return authApi.authUser(companyId, MANAGER_ACCOUNT, MANAGER_PASSWORD, timeStamp, new DeviceInfo(LoginActivity.this).allInfo(), sdkSum);
                }
                return Flowable.error(new XCloudException(jsonObject.optString("message", "服务器接口错误，请联系管理员...")));
            }
        }).flatMap(new Function<JSONObject, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(JSONObject jsonObject) throws Exception {

//                LogUtil.e("登录",jsonObject.toString());

                int status = jsonObject.optInt("status");
                if (status != 1) {
                    return Flowable.error(new UserAuthException(jsonObject.optString("message", "未知接口异常，请联系管理员")));
                }
                return XCloudSDKManager.getInstance().prepareXCloudData(LoginActivity.this, mManagerServer, jsonObject);
            }
        }).flatMap(new Function<JSONObject, Publisher<MainExtraBean>>() {
            @Override
            public Publisher<MainExtraBean> apply(JSONObject jsonObject) throws Exception {
                LogUtil.e("登录",jsonObject.toString());
                return new ProfileHandler(LoginActivity.this, jsonObject, mManagerServer, mPassword).start();
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MainExtraBean>() {
            @Override
            public void accept(MainExtraBean mainExtraBean) throws Exception {
                mPreferences.edit().putString(Globals.USER_NAME, mUserName).putString(Globals.PASSWORD, EncUtils.encrypt(mainExtraBean.getUserInfo().getUuid(), mPassword.getBytes()))
                        .putString(Globals.UUID,mainExtraBean.getUserInfo().getUuid())
                     //   .putString(Globals.USER_TOKEN,mainExtraBean.getUserInfo().getToken())
                        .putBoolean(Globals.SP_MULTI_DEVICES, false).commit();
                getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE).edit().putString(Globals.SP_COMPANY_THEME_CODE, mainExtraBean.getThemeCode()).commit();
                EnterConfig.getInstance().setThemeCode(mainExtraBean.getThemeCode());
                HttpMethods.getInstance().initManagerServer(mManagerServer); //因为登录的时候client被重置了

                onResult("cofcoko\\"+mUserName,mPassword,"172.16.11.61:8000",mainExtraBean.getUserInfo().getUuid());
                startActivity(new MainActivity.MainIntentBuilder(LoginActivity.this).setData(mainExtraBean).isAutoLogin(false).getIntent());
                mWaitingDialog.dismiss();
                finish();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                mWaitingDialog.dismiss();
                ToastUtils.showToast(XCloudSDKManager.getInstance().generateError(throwable));
            }
        });

    }


    public void onResult(final String userName, final String password,String url,String mUUID) {

        if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
            XCloudSignDao xCloudSignDao = EnterDbManager.getInstances().getXCloudSignDao();
            XCloudSign xCloudSign = xCloudSignDao.queryBuilder().where(XCloudSignDao.Properties.Host.eq(url)).build().unique();
            // String mUUID = YspPreferences.getInstance().getSharedPreferences().getString(Globals.UUID, "");
            String encUserName = EncUtils.encrypt(mUUID, userName.getBytes());
            String encPassword = EncUtils.encrypt(mUUID, password.getBytes());
            Log.i("mCardAccountModel", "encUserName: " + encUserName + "  encPassword: " + encPassword);
            if (!TextUtils.isEmpty(encUserName) && !TextUtils.isEmpty(encPassword)) {
                if (xCloudSign != null) {
                    xCloudSign.setUserName(encUserName);
                    xCloudSign.setPassword(encPassword);
                    xCloudSignDao.update(xCloudSign);
                } else {
                    xCloudSign = new XCloudSign(url, encUserName, encPassword, "", "", "");
                    xCloudSignDao.insert(xCloudSign);
                }
            }
        }
    }



    /**
     *AD验证接口
     */
    private void loginADServer(String mUserName,String mPassword) {

       String body = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "  <soap:Body>" +
                "    <ADLogin xmlns=\""+BuildConfig.AD_PATH+"/PortalService"+"/\">" +
                "      <userID>%username%</userID>" +
                "      <userPwd>%password%</userPwd>" +
                "      <domain>cofcoko</domain>" +
                "    </ADLogin>" +
                "  </soap:Body>" +
                "</soap:Envelope>";
       // String url = "http://info.cofcoko.com/PortalService/WebService.asmx?op=ADLogin/";
        String url = BuildConfig.AD_PATH+"/PortalService/WebService.asmx?op=ADLogin/";
        OkHttpClient client = new OkHttpClient();
        //bpmtest01 S8e677778
        final Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.parse("text/xml"), body.replace("%username%", mUserName).replace("%password%", mPassword)))
                .addHeader("Content-Type", "text/xml; charset=utf-8")
                .build();

        try {
            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, final IOException e) {
                    Log.e("response",e.getMessage().toString());
                    mWaitingDialog.dismiss();



                }

                @Override
                public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
//                    final int code = response.code();


                 //   Log.e("response",response.body().string());
                       JSONObject jsonObject= null;
                       try {
                           jsonObject = new JSONObject(String.valueOf(Html.fromHtml(response.body().string())));


                           if (jsonObject.getString("Flag").equals("1")){
                               String SessionID=jsonObject.getString("SessionID");
                               String UserName=jsonObject.getString("UserName");
                               String DomainAccount=jsonObject.getString("DomainAccount");
                           mPreferences.edit()
                                   .putString("ADUserName",UserName)
                                   .putString("ADDomainAccount",DomainAccount)
                                   .putString("SessionID",SessionID).commit();
                           initHttp();
                           } else {
                               Log.e("Message",jsonObject.getString("Message"));
                               Message msg =Message.obtain();
                               msg.obj = jsonObject.getString("Message");
                               msg.what=1;   //标志消息的标志
                               handler.sendMessage(msg);
                               mWaitingDialog.dismiss();
                           }

                       } catch (JSONException e) {
                           e.printStackTrace();
                       }








                }
            });
        } catch (Exception e) {

        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    ToastUtils.showToast((String) msg.obj);
                    break;
            }
        }
    };


}
